import { Node, createEditor, Editor, Transforms, Text, Path } from "slate";

export const onKeyDown = (e, editor) => {
    if (e.key !== 'Enter') {
        return ;
    }
    e.preventDefault();
    OperateTable(editor, 'insertTop');
}

export const OperateTable = (editor, type) => {

    if (type === 'insertTop' || type === 'insertBottom') {
        const [match] = Editor.nodes(editor, {
            match: n => n.type === 'table-row'
        });

        const at = match[1];
        if (type === 'insertBottom') {
            at[1] = at[1] + 1
        }
        
        let currentRowData = match[0];

        // TODO 好别扭的对象、数组拷贝
        const newRwoData = {
            type: currentRowData.type,
            children: currentRowData.children.map(child => {
                let temp = {
                    'type': child.type,
                    children: [{
                        text: ''
                    }]
                }
                return temp;
            })
        }


        Transforms.insertNodes(editor, newRwoData, {
            at: at
        });

    }

    if (type === 'insertLeft' || type === 'insertRight') {
        const [matchCell] = Editor.nodes(editor, {
            match: n => n.type === 'table-cell'
        });

        const [matchTable] = Editor.nodes(editor, {
            match: n => n.type === 'table'
        });

        let newCellData = {
            type: 'table-cell',
            children: [{
                text: ''
            }]
        }

        const at = matchCell[1];
        matchTable[0].children.forEach((element, i) => {
            let newAt = at.slice();
            newAt[newAt.length-2] = i;  // 修改行数
            if (type === 'insertRight') {
                newAt[newAt.length-1] = newAt[newAt.length-1] +1;
            }
            
            Transforms.insertNodes(editor, newCellData, {
                at: newAt
            });
        });

return ;
        // const at = matchCell[1];
        // // if (type === 'insertBottom') {
        // //     at[1] = at[1] + 1
        // // }
        
        // let currentRowData = match[0];

        // console.log(currentRowData);

        // // TODO 好别扭的对象、数组拷贝
        // const newRwoData = {
        //     type: currentRowData.type,
        //     children: currentRowData.children.map(child => {
        //         let temp = {
        //             'type': child.type,
        //             children: [{
        //                 text: ''
        //             }]
        //         }
        //         return temp;
        //     })
        // }


        // Transforms.insertNodes(editor, newRwoData, {
        //     at: at
        // });

    }
}